<template>
	<view class="container">
		<cu-custom bgColor="bg-gradual-pink" :isBack="false">
			<block slot="content">{{ barTitle }}</block>
		</cu-custom>
		<!-- <tm-menubars title="写作" iconColor="white" color="transparent"></tm-menubars> -->

		<tm-message ref="toast"></tm-message>

		<view class="page-body">
			<view class='wrapper'>
				<view class='toolbar' @tap="format" style="height: 120px;overflow-y: auto;">
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold">
					</view>
					<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic">
					</view>
					<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
						data-name="underline"></view>
					<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian"
						data-name="strike"></view>
					<!-- #ifndef MP-BAIDU -->
					<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi"
						data-name="align" data-value="left"></view>
					<!-- #endif -->
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi"
						data-name="align" data-value="center"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi"
						data-name="align" data-value="right"></view>
					<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi"
						data-name="align" data-value="justify"></view>
					<!-- #ifndef MP-BAIDU -->
					<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height"
						data-name="lineHeight" data-value="2"></view>
					<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing"
						data-name="letterSpacing" data-value="2em"></view>
					<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju"
						data-name="marginTop" data-value="20px"></view>
					<view :class="formats.marginBottom ? 'ql-active' : ''" class="iconfont icon-723bianjiqi_duanhouju"
						data-name="marginBottom" data-value="20px"></view>
					<!-- #endif -->

					<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>

					<!-- #ifndef MP-BAIDU -->
					<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font"
						data-name="fontFamily" data-value="Pacifico"></view>
					<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize"
						data-name="fontSize" data-value="24px"></view>
					<!-- #endif -->
					<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color"
						data-name="color" data-value="#0000ff"></view>
					<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
						class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00"></view>
					<view class="iconfont icon-date" @tap="insertDate"></view>
					<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie"
						data-name="list" data-value="ordered"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
						data-name="list" data-value="bullet"></view>

					<view class="iconfont icon-undo" @tap="undo"></view>
					<view class="iconfont icon-redo" @tap="redo"></view>

					<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					<view class="iconfont icon-charutupian" @tap="insertImage"></view>
					<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1"
						data-name="header" :data-value="1"></view>
					<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao"
						data-name="script" data-value="sub"></view>
					<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao"
						data-name="script" data-value="super"></view>

					<view class="iconfont icon-shanchu" @tap="clear"></view>

					<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl"
						data-name="direction" data-value="rtl"></view>


					<view class="iconfont" data-value="publish" @click="publishArticle()">
						<tm-icons name="icon-paper-plane" size="38"></tm-icons>
					</view>
				</view>

				<view class="editor-wrapper">
					<editor id="editor" class="ql-container" placeholder="开始输入..." show-img-size show-img-toolbar
						show-img-resize @statuschange="onStatusChange" :read-only="readOnly" @ready="onEditorReady">
					</editor>
				</view>
			</view>
		</view>

		<!-- 弹窗 -->
		<view class="form-modal" :class="modalName == 'publishModal' ? 'show' : ''">
			<view class="form-dialog">
				<view class="form-bar bg-white justify-between text-align-left">
					<view class="content">发布文章</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>

				<tm-form @submit="submit" ref="formData" @request="success" method="post"
					url="https://mockapi.eolinker.com/Uj8WNQX0d65502098df8ecc1f06348d7aac9364b4d08923/gongyingshang/fabu">
					<tm-sheet :shadow="12" :padding="[12, 12]" :margin="[12, 12]">
						<tm-input name="title" required title="文章标题" v-model="form.articleTitle"></tm-input>
						<tm-pickers rang-key="categoryName" :list="categories" @confirm="selectedCateory">
							<tm-input name="categoryName" required title="文章分类" placeholder="请选择分类" disabled
								:value="category.categoryName" right-icon="icon-angle-right"></tm-input>
						</tm-pickers>

						<!-- <view class="mx-32 my-12 border-b-1  pb-12 flex-between"
							:class="$store.state.tmVuetify.black ? 'bk' : ''">
							<text class="text-size-n">文章标签</text>
							<tm-dropDownMenu @confirm="confirm" :list="list2" style="width: 200px;"></tm-dropDownMenu>
						</view> -->

						<view class="mx-32 my-12 border-b-1  pb-12 flex-between">
							是否置顶 <tm-switch :text="['是','否']" color="bg-gradient-orange-accent"
								v-model="isTop"></tm-switch>
							是否推荐 <tm-switch :text="['是','否']" color="bg-gradient-blue-accent"
								v-model="isFeatured"></tm-switch>
						</view>


						<!-- <tm-input name="price" required title="价格" input-type="digit" v-model="reqData.price"
							suffix="万"></tm-input> -->

						<!-- 	<tm-input name="pailiang" input-type="number" title="车辆排量" placeholder="请输入"
							v-model="reqData.pailiang" suffix="升(L)"></tm-input> -->
						<!-- <tm-input :vertical="true" required :height="150" input-type="textarea"
							bg-color="grey-lighten-5" :maxlength="200" title="车辆描述" placeholder="请输入,不超过200字符"
							v-model="reqData.beizu"></tm-input> -->
						<view class="mx-32 my-12 border-b-1  pb-12 flex-between"
							:class="$store.state.tmVuetify.black ? 'bk' : ''">
							<text class="text-size-n ">发布形式</text>
							<tm-groupradio name="shiguche" @change="shiguchechange">
								<tm-radio :name="item.title" v-for="(item, index) in shifoushiguche" :key="index"
									v-model="item.checked" :label="item.title"></tm-radio>
							</tm-groupradio>
						</view>

						<view class="px-24">
							<tm-button navtie-type="form" theme="bg-gradient-blue-accent" block @click="">发布</tm-button>
							<!-- <view class="py-32 text-size-s text-grey text-align-center">请注意资料的上传，必填项。</view> -->
						</view>
						<!-- <tm-button @click="getData" block theme="pink">手动获取表单数据,无验证</tm-button> -->
					</tm-sheet>
				</tm-form>
			</view>
		</view>
	</view>
</template>

<!-- 富文本编辑器 -->
<script>
	import tmIcons from '@/tm-vuetify/components/tm-icons/tm-icons.vue';
	import storage from "@/utils/storage.js"
	import constant from "@/utils/constant.js"
	import {
		getAllCategories
	} from '@/api/article/category.js';
	import {
		addOrEditArticle,
		getAllArticles,
		getArticlesByCategoryId
	} from '@/api/article/article.js';

	export default {
		components: {
			tmIcons
		},
		data() {
			return {
				barTitle: '写作',
				modalName: null,
				readOnly: false,
				formats: {},
				form: {
					status: 1
				},
				isTop: false,
				isFeatured: false,
				categories: [],
				chelianglis: [{
						title: "SUV",
						id: 21
					},
					{
						title: "面包车",
						id: 31
					},
					{
						title: "跑车",
						id: 41
					},
					{
						title: "轿车",
						id: 51
					},
					{
						title: "房车",
						id: 61
					},
				],
				list2: [{
					title: '选择标签',
					children: [{
						title: "默认排序",
						model: "checkbox",
						name: "desc",
						children: [{
								title: "默认排序",
								id: '1-1'
							},
							{
								title: "最近更新",
								id: '1-2'
							},
							{
								title: "信誉值最高",
								id: '1-3'
							},
							{
								title: "信誉值最高",
								id: '1-4'
							}
						]
					}]
				}],
				shifoushiguche: [{
						title: "公开",
						checked: true,
						value: 1
					},
					{
						title: "密码",
						checked: null,
						value: 2
					},
				],
				bam: [{
						title: "超大",
						id: 1,
						checked: false
					},
					{
						title: "钻石车",
						id: 3,
						checked: false
					},
					{
						title: "好车",
						id: 4,
						checked: false
					},
				],
				category: {},
				editorCtx: null,
				reqData: {
					uploadImg: [],
					title: "",
					price: "",
					city: [{
						text: "上海市",
						id: 31
					}, {
						text: "市辖区",
						id: 3101
					}, {
						text: "普陀区",
						id: 310107
					}],
					chexing: [{
						title: "跑车",
						id: 41
					}],
					chuchangtime: "",
					pailiang: "",
					beizu: "",
					shiguche: [],
					shangjia: false,
					pingfen: 0,
					gujia: 0,
					zhiding: false,
					timeTep: 0,
					bqm: []
				}
			}
		},
		created() {
			// console.log(this.$store.state)
			// console.log(this.$store.state.tmVuetify.black)
		},
		computed: {
			cityDisplay: function() {
				if (typeof this.reqData.city[0] === 'object') {
					let ds = [];
					this.reqData.city.forEach(item => {
						ds.push(item.text)
					})
					return ds.join('/')
				} else if (typeof this.reqData.city[0] === 'string') {

					return this.reqData.city.join('/')
				}
			}
		},
		methods: {
			hideModal(e) {
				this.modalName = null
			},
			confirm(e) {
				console.log('您选中了的数据为：', e);
			},
			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady() {
				// #ifdef APP-PLUS || MP-WEIXIN || H5
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
				// #endif
			},
			undo() {
				this.editorCtx.undo()
			},
			redo() {
				this.editorCtx.redo()
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				this.editorCtx.format(name, value)
			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			clear() {
				uni.showModal({
					title: '清空编辑器',
					content: '确定清空编辑器全部内容？',
					success: res => {
						if (res.confirm) {
							this.editorCtx.clear({
								success: function(res) {
									console.log("clear success")
								}
							})
						}
					}
				})
			},
			removeFormat() {
				this.editorCtx.removeFormat()
			},
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDates
				})
			},
			selectedCateory(arr) {
				this.category = arr[0].data
				this.form.categoryId = arr[0].data.id;
				this.form.categoryName = arr[0].data.categoryName;
			},
			change(e) {
				console.log("e:", e);
			},
			publishArticle() {
				var that = this;
				this.form.isTop = this.isTop ? 1 : 0
				this.form.isFeatured = this.isFeatured ? 1 : 0
				this.editorCtx.getContents({
					success: function(res) {
						that.form.articleContent = res.text
					},
					fail: function() {
						console.log("失败了")
					},
					complete: function() {
						// console.log("完成了")
					}
				})
				let any = storage.get(constant.article.category);
				if (!any) {
					this.getCategories();
				} else {
					this.categories = any;
				}
				this.modalName = 'publishModal'
			},
			insertImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.editorCtx.insertImage({
							src: res.tempFilePaths[0],
							alt: '图像',
							success: function() {
								console.log('insert image success')
							}
						})
					}
				})
			},
			// 查询所有分类
			async getCategories() {
				await getAllCategories().then(res => {
					if (res.code == 200) {
						this.categories = res.data;
						storage.set(constant.article.category, res.data)
						return res.data
					}
				})
			},
			async submit(e) {
				var that = this;
				console.log(this.form)
				if (e === false) {
					uni.$tm.toast("请填写必填项。")
				}
				await addOrEditArticle(this.form).then(res => {
					if (res.flag) {
						that.$refs.toast.show({
							model: 'success',
							icon: 'icon-wind-smile',
							label: '操作成功'
						})
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/mine'
							});
						}, 1200)
					} else {

					}
				})
			},
			success(e) {
				//提交成功 。
				uni.$tm.toast(e.msg)
			},
			async getData(e) {
				let d = await this.$refs.formData.getFormData();
				uni.showModal({
					title: "数据如下",
					content: JSON.stringify(d),
					showCancel: false
				})
			},
			obTstr(o) {
				if (Array.isArray(o)) {
					if (o.length.length === 0) return "";
					return o.join(",")
				}
				return JSON.stringify(o)
			},
			obTstr2(o) {
				if (Array.isArray(o)) {
					if (o.length.length === 0) return "";
					return o[0]?.title ?? ""
				}
				return ''
			},
			chuchangchange(e) {
				this.$set(this.reqData, 'chuchangtime', e.year + "-" + e.month + "-" + e.day)
			},
			shiguchechange(e) {
				console.log(e)
				if (e[0].checked) {
					this.form.status = e[0].value
				}
			},
		}
	}
</script>

<style>
	@import "./editor-icon.css";

	.page-body {
		height: calc(100vh - var(--window-top) - var(--status-bar-height));
		background: #ffffcc;
	}

	.wrapper {
		height: 100%;
	}

	.editor-wrapper {
		height: calc(100vh - var(--window-top) - var(--status-bar-height) - 140px);
		background: #fff;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
		position: sticky;
		display: grid;
		grid-template-columns: repeat(9, 1fr);
		grid-template-rows: repeat(9, 1fr);
		top: 90px;
	}

	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		min-height: 30vh;
		height: 100%;
		margin-top: 20px;
		font-size: 16px;
		line-height: 1.5;
	}

	.ql-active {
		color: #06c;
	}

	.form-modal {
		position: fixed;
		top: 10%;
		right: 10px;
		bottom: 10%;
		left: 10px;
		z-index: 1110;
		opacity: 0;
		outline: 0;
		-ms-transform: scale(1.185);
		transform: scale(1.185);
		backface-visibility: hidden;
		perspective: 2000upx;
		/* background: rgba(0, 0, 0, 0.6); */
		transition: all 0.3s ease-in-out 0s;
		pointer-events: none;
	}

	.form-modal.show {
		opacity: 1;
		transition-duration: 0.3s;
		-ms-transform: scale(1);
		transform: scale(1);
		overflow-x: hidden;
		overflow-y: auto;
		pointer-events: auto;
	}

	.form-dialog {
		position: relative;
		display: inline-block;
		vertical-align: middle;
		margin-left: auto;
		margin-right: auto;
		/* width: 680upx; */
		/* max-width: 100%; */
		background-color: #f8f8f8;
		border-radius: 10upx;
		overflow: hidden;
	}

	.form-bar {
		display: flex;
		position: relative;
		align-items: center;
		min-height: 80upx;
		justify-content: flex-end;
		border-top-right-radius: 12px;
		border-top-left-radius: 12px;
	}

	.form-bar .action {
		display: flex;
		align-items: center;
		height: 100%;
		justify-content: center;
		max-width: 100%;
	}

	.form-bar .action.border-title {
		position: relative;
		top: -10upx;
	}

	.form-bar .action.border-title text[class*="bg-"]:last-child {
		position: absolute;
		bottom: -0.5rem;
		min-width: 2rem;
		height: 6upx;
		left: 0;
	}

	.form-bar .action.sub-title {
		position: relative;
		top: -0.2rem;
	}

	.form-bar .action.sub-title text {
		position: relative;
		z-index: 1;
	}

	.form-bar .action.sub-title text[class*="bg-"]:last-child {
		position: absolute;
		display: inline-block;
		bottom: -0.2rem;
		border-radius: 6upx;
		width: 100%;
		height: 0.6rem;
		left: 0.6rem;
		opacity: 0.3;
		z-index: 0;
	}

	.form-bar .action.sub-title text[class*="text-"]:last-child {
		position: absolute;
		display: inline-block;
		bottom: -0.7rem;
		left: 0.5rem;
		opacity: 0.2;
		z-index: 0;
		text-align: right;
		font-weight: 900;
		font-size: 36upx;
	}

	.form-bar.justify-center .action.border-title text:last-child,
	.form-bar.justify-center .action.sub-title text:last-child {
		left: 0;
		right: 0;
		margin: auto;
		text-align: center;
	}

	.form-bar .action:first-child {
		margin-left: 30upx;
		font-size: 30upx;
	}

	.form-bar .action text.text-cut {
		text-align: left;
		width: 100%;
	}

	.form-bar .cu-avatar:first-child {
		margin-left: 20upx;
	}

	.form-bar .action:first-child>text[class*="cuIcon-"] {
		margin-left: -0.3em;
		margin-right: 0.3em;
	}

	.form-bar .action:last-child {
		margin-right: 30upx;
	}

	.form-bar .action>text[class*="cuIcon-"],
	.form-bar .action>view[class*="cuIcon-"] {
		font-size: 36upx;
	}

	.form-bar .action>text[class*="cuIcon-"]+text[class*="cuIcon-"] {
		margin-left: 0.5em;
	}

	.form-bar .content {
		position: absolute;
		text-align: center;
		width: calc(100% - 340upx);
		left: 0;
		right: 0;
		bottom: 0;
		top: 0;
		margin: auto;
		height: 60upx;
		font-size: 32upx;
		line-height: 60upx;
		cursor: none;
		pointer-events: none;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}
</style>